﻿using Microsoft.AspNetCore.DataProtection;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using Traceability.App.Applications;
using Traceability.Domain.Repository;

namespace Traceability.App.Extensions
{
    public static class ServiceCollectionExtensions
    {


       


        /// <summary>
        /// 注册上下文
        /// </summary>
        /// <typeparam name="TDbContext"></typeparam>
        /// <param name="services"></param>
        /// <param name="connectionString"></param>
        /// <param name="enableSqlLog"></param>
        /// <returns></returns>
        public static IServiceCollection AddDbContextService<TDbContext>(this IServiceCollection services, string? connectionString, bool enableSqlLog) where TDbContext : DbContext
        {
            return services.AddDbContext<TDbContext>(builder =>
            {

                builder.UseSqlServer(connectionString, action =>
                {


                    action.EnableRetryOnFailure(

                            maxRetryCount: 10,
                            maxRetryDelay: TimeSpan.FromSeconds(60),
                            errorNumbersToAdd: null

                        );

                }).EnableSensitiveDataLogging();
                if (enableSqlLog)
                {

                    builder.UseLoggerFactory(LoggerFactory.Create(configure =>
                    {

                        configure
                        .AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information)
                        .AddConsole();

                    }));
                
                }

            });
        
        
        }



        /// <summary>
        /// 依赖注入服务类
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddServicess(this IServiceCollection services)
        {

            services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
            services.AddMediatR(x => x.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));
            services.AddAutoMapper(typeof(MappingProfile));


            services.AddControllers();

            services.AddEndpointsApiExplorer();
            
            return services;
        }


      


    }
}
